package com.gzdh.tang.qimei.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzdh.tang.comm.handler.IPayRuleHandler;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.modu.entity.Fk;
import com.gzdh.tang.modu.entity.MacMainpSbruan;
import com.gzdh.tang.modu.service.FkService;
import com.gzdh.tang.modu.service.MacMainpSbruanService;
import com.gzdh.tang.qimei.model.*;
import com.gzdh.tang.qimei.util.ByteUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("qimei")
@Slf4j
public class QiMeiController {

    @Autowired
    FkService fkService;

    @Autowired
    MacMainpSbruanService macMainpSbruanService;


    @Value(value = "${file.uploadType}")
    private String uploadType;

    @Value(value = "${file.path.upload}")
    private String uploadpath;

    /**
     * 先判断消费类型，
     * 如果是现金，直接写reserve记录
     * 如果是刷卡，判断卡上是否有补贴记录，如果没有补贴金额得则使用自购金额
     *
     * @param lineConsumeReq
     * @return
     */
    @RequestMapping("/consumptionTerminal/onLineConsume")
    public QiMeiResult<Object> onLineConsume(@RequestBody LineConsumeReq lineConsumeReq) throws Exception {
        QiMeiResult<Object> result = new QiMeiResult<>();
        LineConsumeRes lineConsumeRes = new LineConsumeRes();
        macMainpSbruanService.getDeviceSign(lineConsumeReq.getDeviceId());
//        log.info(lineConsumeReq.toString());

        try {
            String imgPath = saveImg("data:image/jpeg;base64," + lineConsumeReq.getMenuIDPicture(), null);
            LinConsumeRModel linConsumeRModel = new LinConsumeRModel();
            IPayRuleHandler ruleHandler = (IPayRuleHandler) Class.forName("com.gzdh.tang.qimei.rule.QimeiPayRule").newInstance();
            if (lineConsumeReq.getPayWay() == 7) {
                //现金支付，直接写入reserve

            } else if (lineConsumeReq.getPayWay() == 1) {
                System.out.println("刷卡支付");
                //刷卡支付
                byte[] cardsn = ByteUtil.intToBytes(Integer.parseUnsignedInt(lineConsumeReq.getIdentifiedId()));
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cardSn", ByteUtil.bytesToHexString(cardsn));
                jsonObject.put("req", lineConsumeReq);
                jsonObject.put("imgPath", imgPath);
                JSONObject resJson = ruleHandler.toCardPay(jsonObject);
                linConsumeRModel = resJson.toJavaObject(LinConsumeRModel.class);
            } else if (lineConsumeReq.getPayWay() == 11) {
                System.out.println("刷臉支付");
                //支付宝刷脸操作
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("faceCode", lineConsumeReq.getCode());
                jsonObject.put("req", lineConsumeReq);
                jsonObject.put("imgPath", imgPath);
                JSONObject resJson = ruleHandler.toFacePay(jsonObject);
                linConsumeRModel = resJson.toJavaObject(LinConsumeRModel.class);
            } else if (lineConsumeReq.getPayWay() == 12) {
                System.out.println("開始掃碼支付");
                //電子卡支付
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", lineConsumeReq.getCode());
                jsonObject.put("price", new BigDecimal(lineConsumeReq.getMoney()).divide(new BigDecimal(100)).toPlainString());
                jsonObject.put("deviceId", lineConsumeReq.getDeviceId());
                jsonObject.put("req", lineConsumeReq);
                jsonObject.put("imgPath", imgPath);
                JSONObject resJson = ruleHandler.toQrPay(jsonObject);
                linConsumeRModel = resJson.toJavaObject(LinConsumeRModel.class);
            }
            lineConsumeRes.setUserId(Integer.valueOf(linConsumeRModel.getFk().getCardno()));
            lineConsumeRes.setUserPK(Integer.valueOf(linConsumeRModel.getFk().getCardno()));
            lineConsumeRes.setUserName(linConsumeRModel.getFk().getName());
            lineConsumeRes.setAccount(new BigDecimal(linConsumeRModel.getFk().getKye()).multiply(new BigDecimal(100)).stripTrailingZeros().intValue());
            lineConsumeRes.setConsumptionLogPK(String.valueOf(System.currentTimeMillis()));
            lineConsumeRes.setConsumptionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            result.setResult(lineConsumeRes);
        } catch (Exception e) {
            result.setState(500);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 下载白名单
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping("/consumptionTerminal/getWhiteList")
    public QiMeiResult<Object> getWhiteList(@RequestBody JSONObject jsonObject) {
//        System.out.println("开始下载白名单" + jsonObject.toString());
        QiMeiResult<Object> result = new QiMeiResult<>();
        WhiteListRes whiteListRes = new WhiteListRes();
        String deviceId = jsonObject.getString("deviceId");
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>()
                .lambda().eq(MacMainpSbruan::getMac, deviceId));
//        int fkCount = fkService.getCount(macMainpSbruan.getId());
        List<Fk> ifkPage = fkService.getFkByPage(jsonObject.getInteger("pageNum"),
                jsonObject.getInteger("pageSize"), macMainpSbruan.getId());
        List<WhiteListRes.WhiteListArr> whiteListArrList = new ArrayList<>();
        for (Fk goo : ifkPage) {
//        for (int i = 0; i < 1000; i++) {
//            Fk goo = fkList.get(i);
//            byte[] cardsn = ByteUtil.hexStringToByte(goo.getCardsn().trim().toUpperCase());
            WhiteListRes.WhiteListArr whiteListArr = new WhiteListRes.WhiteListArr();
            whiteListArr.setN(goo.getName());
            whiteListArr.setU(goo.getCardno());
            whiteListArr.setM(goo.getCardno());
            whiteListArr.setI(Long.parseLong(goo.getCardsn().trim().toUpperCase(), 16) + "");
            whiteListArr.setP(goo.getCardno());
            whiteListArrList.add(whiteListArr);
        }
        whiteListRes.setRows(whiteListArrList);
        whiteListRes.setTotal(whiteListArrList.size());
        result.setResult(whiteListRes);
        return result;
    }

    private String saveImg(String base64Data, String name) {
//        log.info("==上传图片==");
//        log.info("==接收到的数据==" + base64Data);
        String ctxPath = uploadpath;
        String fileName = null;
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        if (base64Data == null || "".equals(base64Data)) {
//            return Result.error("上传失败，上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");//将字符串分成数组
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
//                return Result.error(401, "上传失败，数据不合法");
            }
        }
        String suffix = "";//图片后缀，用以识别哪种格式数据
        //编码的jpeg图片数据
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/jpg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            //编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            //编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".png";
        } else {
//            return Result.error("上传图片格式不合法");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    //调整异常数据
                    b[i] += 256;
                }
            }
            String filePath = "";
            filePath = ctxPath + File.separator;
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            Random r = new Random(1);
            String orgName = String.valueOf(r.nextInt(100));
//            orgName = CommonUtils.getFileName(orgName);
//            if (orgName.indexOf(".") != -1) {
            if (name != null) {
                fileName = name;
            } else {
                fileName = orgName + "_" + System.currentTimeMillis()
                        + suffix;
            }

//            } else {
//                fileName = orgName + "_" + System.currentTimeMillis();
//            }
            String savePath = file.getPath() + File.separator + fileName;
            OutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();
//            String imgurl=fileName;
            //imageService.save(imgurl);
//            return Result.ok(fileName);
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
//            return Result.error("上传图片失败");
        }
        return "";
    }
}
